package com.shenmazong.recever;

import com.shenmazong.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2022/1/19 11:49
 */

@Component
@Slf4j
public class ProductRecever {

    @Autowired
    TemplateEngine templateEngine;

    private Integer index = 0;

    @RabbitListener(queues = "shopper")
    public void onShopper(LoginVo message) {
        log.info("shopper:"+message.getUserName());

        index ++;

        log.info("shopper(send):"+message.getPassWord());
    }

    @RabbitListener(queues = "html")
    public void onHtml(String message) {
        log.info("html:"+message);

        index ++;
        try {
            makeHtml("h-"+index, message);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    void makeHtml(String name, String message) throws FileNotFoundException, UnsupportedEncodingException {
        // 收到产品ID
        // 根据商品的ID从数据库中获取商品的信息，然后放到上下文中

        // 1、创建上下文
        Context context = new Context();

        // 2、准备数据
        Map<String, Object> map = new HashMap<>();
        map.put("name", "alex");
        map.put("age", 20);
        map.put("email", "3210054449@qq.com");
        map.put("message", message);

        context.setVariables(map);

        // 3、输出文件配置
        File dest = new File("E:\\var", name+".html");
        if (dest.exists()) {
            dest.delete();
        }

        // 4、创建存储输入
        PrintWriter writer = new PrintWriter(dest, "UTF-8");

        // 5、调用引擎，生成静态页面
        templateEngine.process("hello", context, writer);

    }
}
